package ehcache.service;

import ehcache.dao.UserRepository;
import ehcache.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.cache.annotation.Cacheable;

import java.util.List;

@CacheConfig(cacheNames = {"ehCache"})
@Service
public class UserService{

    @Autowired
    private UserRepository userRepository;


    @CachePut(key = "#user.id")
    public User insert(User user){
        User saveUser = userRepository.save(user);
        System.out.println("新增了缓存，key为："+user.getId());
        return saveUser;
    }

    @CacheEvict(key = "#id")
    public void deleteById(String id){
        System.out.println("删除缓存，key："+id);
        userRepository.delete(id);
    }

    @CachePut(key = "#user.id")
    public User updateById(User user){
        User udpateUser = userRepository.save(user);
        System.out.println("更新缓存，key："+user.getId());
        return udpateUser;
    }

    @Cacheable(key = "#id")
    public User selectById(String id){
        System.out.println("查询缓存，key："+id);
        return userRepository.findOne(id);
    }

    public List<User> selectList(){
        return userRepository.findAll();
    }
}
